package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.CountsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TypeVO;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserLikeService {

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserLikeService userLikeService;

    @Autowired
    private UserInfoApi userInfoApi;

    @Autowired
    private VisitorsApi visitorsApi;

    /**
     * 统计互相喜欢，喜欢，粉丝的数量
     *
     * @return
     */
    public CountsVo counts() {
        //1.调用api查看互相喜欢，喜欢，粉丝的数量
        CountsVo vo = userLikeApi.counts(UserHolder.getUserId());
        //2.构建条件查询互相喜欢的数量
        //查询我喜欢的人
        List<UserLike> list = userLikeApi.finds(UserHolder.getUserId());
        //获取所有我喜欢的人的id
        List<Long> userIds = CollUtil.getFieldValues(list, "likeUserId", Long.class);
        //遍历集合，通过redis交集查询出是否双向喜欢
        List<Long> longList = new ArrayList<>();
        int count = 0;
        for (Long userId : userIds) {
            //判断我喜欢的人是否也喜欢我，查询redis中他喜欢的人是否有我，有我就加1
            Boolean flag = redisTemplate.opsForSet().isMember(Constants.USER_LIKE_KEY + userId, UserHolder.getUserId().toString());
            if (flag) {
                count++;
                //如果成立把id存进集合中
                longList.add(userId);
            }
        }
        //把获取到的互相喜欢的id集合存到vo中
        vo.setEachLoveCounts(longList);
        vo.setEachLoveCount(longList.size());
        return vo;
    }

    @Autowired
    private RecommendUserApi recommendUserApi;

    /**
     * @param type     类型  1 互相关注 2 我关注 3 粉丝 4 谁看过我
     * @param page     页数
     * @param pagesize 每页几条
     * @param nickname 昵称
     * @return
     */
    public PageResult typeSum(String type, Integer page, Integer pagesize, String nickname) {
        switch (type) {
            case "1":
                //1.调用UserLikeService的count方法获取互相喜欢的人的id
                CountsVo counts1 = userLikeService.counts();
                List<Long> userIds = counts1.getEachLoveCounts();
                return getPageResult(page, pagesize, nickname, userIds);
            case "2":
                //1.调用UserLikeService的count方法获取我喜欢的人的id
                CountsVo counts2 = userLikeService.counts();
                List<Long> loves = counts2.getLoveCounts();
                return getPageResult(page, pagesize, nickname, loves);
            case "3":
                //1.调用UserLikeService的count方法获取喜欢我的人的id
                CountsVo counts3 = userLikeService.counts();
                List<Long> fans = counts3.getFanCounts();
                return getPageResult(page, pagesize, nickname, fans);
            case "4":
                //1.设置一份查看时间到redis中
                String key = Constants.VISITORS_USER;
                String hashKey = UserHolder.getUserId().toString();
                redisTemplate.opsForHash().put(key, hashKey, String.valueOf(System.currentTimeMillis()));
                //2.调用api查询看过我的人id
                List<Visitors> visitors = visitorsApi.queryVisitorsList(null, UserHolder.getUserId());
                List<Long> ids = CollUtil.getFieldValues(visitors, "visitorUserId", Long.class);
                return getPageResult(page, pagesize, nickname, ids);
            default:
                return new PageResult();
        }
    }

    /**
     * 封装的公用方法
     *
     * @param page
     * @param pagesize
     * @param nickname
     * @param userIds
     * @return
     */
    private PageResult getPageResult(Integer page, Integer pagesize, String nickname, List<Long> userIds) {
        //2.查看每个人的用户详情
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        //如果数据为空，返回一个空的PageResult
        if (CollUtil.isEmpty(userIds)) {
            return new PageResult();
        }
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(userIds, userInfo);
        //3.封装vo返回
        List<TypeVO> vos = new ArrayList<>();
        for (Long userId : userIds) {
            UserInfo info = infoMap.get(userId);
            if (info != null) {
                TypeVO vo = TypeVO.init(info);
                //设置是否喜欢
                vo.setAlreadyLove(true);
                //设置缘分值 调用api查询当前id和对象id的缘分值对象
                RecommendUser user = recommendUserApi.personalInfo(UserHolder.getUserId(), userId);
                //如果没有缘分值设置一个默认的
                if (user.getScore() == null) {
                    user.setScore(99D);
                }
                vo.setMatchRate(user.getScore().intValue());
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, Long.valueOf(userIds.size()), vos);
    }
}
